﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Customs.Components.KDT.SXXK.Info;
using Microsoft.ApplicationBlocks.Data;

namespace Customs.Components.KDT.SXXK
{
    public class NguyenPhuLieuDangKy : NguyenPhuLieuDangKyInfo
    {
        public void Load(NguyenPhuLieuDangKyInfo entityInfo)
        {
            this._SoTiepNhan = entityInfo.SoTiepNhan;
            this._MaHaiQuan = entityInfo.MaHaiQuan;
            this._NamTiepNhan = entityInfo.NamTiepNhan;
            this._NgayTiepNhan = entityInfo.NgayTiepNhan;
            this._SoTiepNhanChungTu = entityInfo.SoTiepNhanChungTu;
            this._NgayTiepNhanChungTu = entityInfo.NgayTiepNhanChungTu;
            this._MaDoanhNghiep = entityInfo.MaDoanhNghiep;
            this._MaDaiLy = entityInfo.MaDaiLy;
            this._TrangThaiXL = entityInfo.TrangThaiXL;
            this._AppSource = entityInfo.AppSource;

            this._NPLInfoCollection = entityInfo.NPLInfoCollection;
        }

        //-----------------------------------------------------------------------------------------
        public long GetSoTiepNhan(SqlTransaction transaction)
        {
            string spName = "KDT_CapSo_NPL";
            SqlParameter[] parameters = new SqlParameter[2];

            parameters[0] = new SqlParameter("@MaHQTN", SqlDbType.Char, 6);
            parameters[0].Direction = ParameterDirection.Input;
            parameters[0].Value = this._MaHaiQuan;

            parameters[1] = new SqlParameter("@NamTN", SqlDbType.SmallInt);
            parameters[1].Direction = ParameterDirection.Input;
            parameters[1].Value = this._NamTiepNhan;

            return Convert.ToInt64(SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, parameters));            
        }
        public void Load()
        {
            SqlDataReader reader = this.Select();
            if (reader.Read())
            {
                if (!reader.IsDBNull(reader.GetOrdinal("SoTiepNhan"))) this.SoTiepNhan = reader.GetInt64(reader.GetOrdinal("SoTiepNhan"));
                if (!reader.IsDBNull(reader.GetOrdinal("MaHaiQuan"))) this.MaHaiQuan = reader.GetString(reader.GetOrdinal("MaHaiQuan"));
                if (!reader.IsDBNull(reader.GetOrdinal("NamTiepNhan"))) this.NamTiepNhan = reader.GetInt16(reader.GetOrdinal("NamTiepNhan"));
                if (!reader.IsDBNull(reader.GetOrdinal("NgayTiepNhan"))) this.NgayTiepNhan = reader.GetDateTime(reader.GetOrdinal("NgayTiepNhan"));
                if (!reader.IsDBNull(reader.GetOrdinal("MaDoanhNghiep"))) this.MaDoanhNghiep = reader.GetString(reader.GetOrdinal("MaDoanhNghiep"));
                if (!reader.IsDBNull(reader.GetOrdinal("TrangThaiXuLy"))) this.TrangThaiXL = reader.GetInt32(reader.GetOrdinal("TrangThaiXuLy"));
                reader.Close();
            }
        }

        public SqlDataReader Select()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString;
            StringBuilder query = new StringBuilder();
            query.Append("SELECT ");
            query.Append("So_TNDKDT AS [SoTiepNhan], ");
            query.Append("Ma_HQTN AS [MaHaiQuan], ");
            query.Append("Nam_TN AS [NamTiepNhan], ");
            query.Append("Ngay_TN AS [NgayTiepNhan], ");
            query.Append("Ma_DV AS [MaDoanhNghiep], ");
            query.Append("Ma_DVKB AS [MaDaiLy], ");
            query.Append("TrangThaiXL AS [TrangThaiXuLy], ");
            query.Append("AppSource ");
            query.Append("FROM dbo.[DNPLDK] ");
            query.Append("WHERE ");
            query.Append("So_TNDKDT = @SoTiepNhan AND Ma_HQTN = @MaHaiQuan AND Nam_TN = @NamTiepNhan");

            SqlParameter[] parameters = new SqlParameter[3];
            parameters[0] = new SqlParameter("@SoTiepNhan", SqlDbType.BigInt);
            parameters[0].Value = this.SoTiepNhan;

            parameters[1] = new SqlParameter("@MaHaiQuan", SqlDbType.Char, 6);
            parameters[1].Value = this.MaHaiQuan;

            parameters[2] = new SqlParameter("@NamTiepNhan", SqlDbType.SmallInt);
            parameters[2].Value = this.NamTiepNhan;

            return SqlHelper.ExecuteReader(connectionString, CommandType.Text, query.ToString(), parameters);
        }
        //-----------------------------------------------------------------------------------------

        public void Insert(SqlTransaction transaction)
        {
            StringBuilder query = new StringBuilder();
            query.Append("INSERT INTO DNPLDK (");
            query.Append("So_TNDKDT, ");
            query.Append("Ma_HQTN, ");
            query.Append("Nam_TN, ");
            query.Append("Ngay_TN, ");
            query.Append("So_TNCT, ");
            query.Append("Ngay_TNCT, ");
            query.Append("MA_DV, ");
            query.Append("Ma_DVKB, ");
            query.Append("TrangThaiXL, ");
            query.Append("AppSource ) ");

            query.Append("VALUES ( ");

            query.Append("@So_TNDKDT, ");
            query.Append("@Ma_HQTN, ");
            query.Append("@Nam_TN, ");
            query.Append("@Ngay_TN, ");
            query.Append("@So_TNCT, ");
            query.Append("@Ngay_TNCT, ");
            query.Append("@MA_DV, ");
            query.Append("@Ma_DVKB, ");
            query.Append("@TrangThaiXL, ");
            query.Append("@AppSource )");

            SqlParameter[] parameters = new SqlParameter[10];

            parameters[0] = new SqlParameter("@So_TNDKDT", SqlDbType.BigInt);
            parameters[0].Value = this._SoTiepNhan;

            parameters[1] = new SqlParameter("@Ma_HQTN", SqlDbType.Char, 6);
            parameters[1].Value = this._MaHaiQuan;

            parameters[2] = new SqlParameter("@Nam_TN", SqlDbType.SmallInt);
            parameters[2].Value = this._NamTiepNhan;

            parameters[3] = new SqlParameter("@Ngay_TN", SqlDbType.DateTime);
            parameters[3].Value = this._NgayTiepNhan;

            parameters[4] = new SqlParameter("@So_TNCT", SqlDbType.BigInt);
            parameters[4].Value = this._SoTiepNhanChungTu;

            parameters[5] = new SqlParameter("@Ngay_TNCT", SqlDbType.DateTime);
            parameters[5].Value = this._NgayTiepNhanChungTu;

            parameters[6] = new SqlParameter("@MA_DV", SqlDbType.VarChar, 14);
            parameters[6].Value = this._MaDoanhNghiep;

            parameters[7] = new SqlParameter("@Ma_DVKB", SqlDbType.VarChar, 14);
            parameters[7].Value = this._MaDaiLy;

            parameters[8] = new SqlParameter("@TrangThaiXL", SqlDbType.Int);
            parameters[8].Value = this._TrangThaiXL;

            parameters[9] = new SqlParameter("@AppSource", SqlDbType.NVarChar, 50);
            parameters[9].Value = this._AppSource;

            SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, query.ToString(), parameters);
        }

        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Đăng ký thông tin nguyên phụ liệu.
        /// </summary>
        /// <returns>Số tiếp nhận</returns>
        public long InsertFull()
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString))
            {
                conn.Open();
                SqlTransaction transactionKDT = conn.BeginTransaction();
                try
                {
                    if (this.SoTiepNhan > 0)
                        HuyThongTin(this.SoTiepNhan, this.MaHaiQuan, this.MaDoanhNghiep, this.NamTiepNhan, transactionKDT);
                    this.NgayTiepNhan = DateTime.Today;
                    this.NamTiepNhan = (short)this.NgayTiepNhan.Year;                    
                    long soTiepNhan = this.GetSoTiepNhan(transactionKDT);
                    this._SoTiepNhan = soTiepNhan;
                    this.Insert(transactionKDT);
                    // Danh sách nguyên phụ liệu.
                    NguyenPhuLieu npl = new NguyenPhuLieu();
                    int i = 1;
                    foreach (NguyenPhuLieuInfo nplInfo in this._NPLInfoCollection)
                    {
                        nplInfo.SoTiepNhan = soTiepNhan;
                        nplInfo.MaHaiQuan = this._MaHaiQuan;
                        nplInfo.NamTiepNhan = this._NamTiepNhan;
                        nplInfo.MaDoanhNghiep = this._MaDoanhNghiep;
                        nplInfo.SoThuTuHang = i;
                        i++;
                    }

                    npl.InsertTransaction(transactionKDT, this._NPLInfoCollection);
                    transactionKDT.Commit();
                    return soTiepNhan;
                }
                catch (Exception ex)
                {
                    transactionKDT.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        public static void HuyThongTin(long soTiepNhan, string maHaiQuan, string maDoanhNghiep, int namTiepNhan,SqlTransaction transaction)
        {
            NguyenPhuLieuDangKy npldk = new NguyenPhuLieuDangKy();
            npldk.SoTiepNhan = soTiepNhan;
            npldk.NamTiepNhan = (short)namTiepNhan;
            npldk.MaHaiQuan = maHaiQuan;
            npldk.Load();
            if (npldk.TrangThaiXL == 1)
                throw new Exception("123DaDuyet321");
            // Xóa các nguyên phụ liệu.
            NguyenPhuLieu.Delete(transaction, soTiepNhan, maHaiQuan, maDoanhNghiep, namTiepNhan);

            // Xóa thông tin khai báo.
            Delete(transaction, soTiepNhan, maHaiQuan, maDoanhNghiep, namTiepNhan);

        }

        public static bool HuyThongTinKhaiBao(long soTiepNhan, string maHaiQuan, string maDoanhNghiep, int namTiepNhan)
        {
            bool ret;
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString))
            {
                conn.Open();
                SqlTransaction transaction = conn.BeginTransaction();
                try
                {
                    NguyenPhuLieuDangKy npldk = new NguyenPhuLieuDangKy();
                    npldk.SoTiepNhan = soTiepNhan;
                    npldk.NamTiepNhan = (short)namTiepNhan;
                    npldk.MaHaiQuan = maHaiQuan;
                    npldk.Load();
                    if (npldk.TrangThaiXL == 1)
                        throw new Exception("123DaDuyet321");
                    // Xóa các nguyên phụ liệu.
                    NguyenPhuLieu.Delete(transaction, soTiepNhan, maHaiQuan, maDoanhNghiep, namTiepNhan);

                    // Xóa thông tin khai báo.
                    Delete(transaction, soTiepNhan, maHaiQuan, maDoanhNghiep, namTiepNhan);
                    transaction.Commit();
                    ret = true;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
            return ret;
        }

        //-----------------------------------------------------------------------------------------
        public static void Delete(SqlTransaction transaction, long soTiepNhan, string maHaiQuan, string maDoanhNghiep, int namTiepNhan)
        {
            string query = string.Format("DELETE FROM DNPLDK WHERE SO_TNDKDT = {0} AND MA_HQTN = '{1}' AND MA_DV = '{2}' AND NAM_TN = {3}", soTiepNhan, maHaiQuan.PadRight(6), maDoanhNghiep, namTiepNhan);
            SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, query);
        }

        //-----------------------------------------------------------------------------------------
        public bool DaDuyet()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString;
            string query = string.Format("SELECT ISNULL(TrangThaiXL, 0) AS TrangThaiXL FROM DNPLDK WHERE SO_TNDKDT = {0} AND MA_HQTN = '{1}' AND MA_DV = '{2}' AND NAM_TN = {3}", this._SoTiepNhan, this._MaHaiQuan.PadRight(6), this.MaDoanhNghiep, this._NamTiepNhan);
            object obj = SqlHelper.ExecuteScalar(connectionString, CommandType.Text, query);
            if (obj != null)
            {
                return Convert.ToInt32(obj) == 1;
            }
            return false;
        }
    }
}